<template>
  <div>
    <panel class="regular">
      <template slot="search">
        <header class="has-checkout">
          <span>固定班制表</span> <el-checkbox v-model="holidaysIsValid">节假日是否生效</el-checkbox>
        </header>
<!--        <button @click="save('formRef')">校验</button>-->
        <el-form :model="formData" :rules="formData.fixedTableDataRules" ref="formRef">
          <el-table stripe :data="formData.fixedTableData" :header-cell-style="{ 'background-color': 'rgba(201, 215, 242, 1)' }">
            <!--          <el-table-column type="selection" width="60" align="center"> </el-table-column>-->
            <el-table-column prop="name" label="工作日" >
            </el-table-column>
            <el-table-column prop="weekName" label="班次" >
              <template slot-scope="scope">
                <el-form-item :prop="'fixedTableData.' + scope.$index + '.weekId'" :rules="formData.fixedTableDataRules.weekId">
                  <!-- 使用 scoped slot 渲染 el-select 组件 -->
                  <el-select @change="selChange" v-model="scope.row.weekId" placeholder="请选择">
                    <el-option-group
                        v-for="group in classesList"
                        :key="group.label"
                        :label="group.label">
                      <el-option
                          v-for="item in group.options"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                        <span style="float: left">{{ item.name }}</span>
                        <span v-if="item.id!=-100" style="float: right; color: #8492a6; font-size: 13px">{{ item.time0 + "~"+ item.time1}}</span>
                      </el-option>
                    </el-option-group>
                  </el-select>
                </el-form-item>

              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </template>
      <template slot="table" >
        <section class="group-type">
          <header>特殊日期设置</header>
          <el-table height="300" stripe :data="specialDatesTableData.values" :header-cell-style="{ 'background-color': 'rgba(201, 215, 242, 1)' }">
            <el-table-column type="index" label="序号" width="100" align="center"> </el-table-column>
            <el-table-column prop="name" label="特殊日期名称">
            </el-table-column>
            <el-table-column prop="name" width="200" label="班次类型" show-overflow-tooltip>
              <template slot-scope="{ row }">
                {{row.workingSchedule.name+": "+row.workingSchedule.time0.substring(0, 5)+"~"+row.workingSchedule.time1.substring(0, 5)}}
              </template>
            </el-table-column>
            <el-table-column prop="date" label="打卡日期"> </el-table-column>
            <el-table-column prop="accountInfo.name" label="创建人"> </el-table-column>
            <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip> </el-table-column>
            <el-table-column prop="name" label="操作">
              <template slot-scope="scope">
                <i class="icon icon-pencil-line" @click="handleChangeSpecialDates(scope.row)"></i>
                <i class="icon icon-trash" @click="handleDel(scope.row)"></i>
              </template>
            </el-table-column>
          </el-table>
          <div style="padding: 10px">
            <el-button
                size="small"
                @click="handleAdd('3')"
                type="handle"
                icon="iconfont-KUI icon-plus-circle"
            >添加其他打卡日期</el-button>
            <el-pagination
                style="display: inline-block;float: right"
                small
                background
                :pager-count="5"
                @size-change="handleSizeChange"
                @current-change="handleRightCurrentChange"
                :current-page.sync="form.pageNumber"
                :page-size="form.pageSize"
                layout="sizes,total, prev, pager, next, jumper"
                :total="specialDatesTableData.totalCount"
                :page-sizes="[10, 20, 50, 100]"
            ></el-pagination>
          </div>
        </section>
      </template>
    </panel>
      <RegularDialog v-if="dialogVisible" :dialogVisible.sync="dialogVisible" ref="dialogRef"
                     @childEvent="handleChildEvent"
                     :attendanceGroupId="attendanceGroupId"
                     :rowData="rowData" :handleType="handleType" :form-type="formType"></RegularDialog>
    </div>
    <!-- <Details v-if="detailsVisible" :detailsVisible.sync="detailsVisible" :handleType="handleType" :tableRow="tableRow" ref="detailsRef"></Details> -->
</template>
<script>
import Panel from "@/components/panel.vue";
import Pagination from "@/components/Pagination/index.vue";
import RegularDialog from './regular-dialog.vue'
import {specialdaysGetlist, specialdaysRemoveteampdata,specialdaysDelete} from "@/api/pcmj/kqz";
import editOrAdd from "@/views/xtpz/attendance-group/components/editOrAdd.vue";
import {workingscheduleGetlist} from "@/api/pcmj/bcgl";
export default {
    components:{
      editOrAdd,
        Panel,
        Pagination,
        RegularDialog
    },
  props: {
    detailRow:{
      type:Object,
      default:()=>{
        return {}
      }
    },
    attendanceGroupId:{
      type:String,
      default:""
    },
    handleTypeSub:{
      type:String,
      default:""
    },
  },
    data() {
      var validateWeekId = (rule, value, callback) => {
        if (value === null) {
          // 请选择班次
          callback(new Error('请选择班次'));
        } else {
          callback();
        }
      };
    return {
      formData:{
        fixedTableDataRules:{
          // weekId: {
          //   required: true,
          //   message: '请选择班次',
          //   tirgger: ['blur', 'change']
          // },
          weekId:[
            {validator: validateWeekId, required: true, trigger: 'change'}
          ]
        },
        fixedTableData: [
          {
            id:"1",
            name:"星期一",
            weekId:null,
            weekName:null,
            checked: false,
          },
          {
            id:"2",
            name:"星期二",
            weekId:null,
            weekName:null,
            checked: false,
          },
          {
            id:"3",
            name:"星期三",
            weekId:null,
            weekName:null,
            checked: false,
          },
          {
            id:"4",
            name:"星期四",
            weekId:null,
            weekName:null,
            checked: false,
          },
          {
            id:"5",
            name:"星期五",
            weekId:null,
            weekName:null,
            checked: false,
          },
          {
            id:"6",
            name:"星期六",
            weekId:null,
            weekName:null,
            checked: false,
          },
          {
            id:"7",
            name:"星期日",
            weekId:null,
            weekName:null,
            checked: false,
          }
        ],
      },
      classesList:[],
      holidaysIsValid:false,
      rowData:null,
      handleType:null,
      dialogVisible:false,
      specialDatesTableData:{},
      formType:'1',
      editId:null,
      form: {
        pageSize: 10,
        pageNumber: 1,
      },
      allSpecialDays:{ values:[]},
      isload:false
    };
  },
  watch:{
    detailRow(newVal,oldVal){
      console.log('oldVal', oldVal);
      console.log('newVal', newVal);

      console.log('detailRow变化了',newVal);
    }
  },
  methods:{
    selChange(){
      console.log(this.formData.fixedTableData);
    },
    save(formName){

    },
    childrenGetParams(){
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          var params={
            holidaysIsValid:this.holidaysIsValid,
            g_Week1Checked: false,
            g_Week1WoringScheduleId:null,
            g_Week2Checked: false,
            g_Week2WoringScheduleId:null,
            g_Week3Checked: false,
            g_Week3WoringScheduleId:null,
            g_Week4Checked: false,
            g_Week4WoringScheduleId:null,
            g_Week5Checked: false,
            g_Week5WoringScheduleId:null,
            g_Week6Checked: false,
            g_Week6WoringScheduleId:null,
            g_Week7Checked: false,
            g_Week7WoringScheduleId:null,
          }
          this.formData.fixedTableData.map((item,index)=>{
            if (item.weekId==-100){
              params["g_Week"+(index+1)+"Checked"]=false
              params["g_Week"+(index+1)+"WoringScheduleId"]=null
            }else {
              params["g_Week"+(index+1)+"Checked"]=true
              params["g_Week"+(index+1)+"WoringScheduleId"]=item.weekId
            }
            // delete item.id
            // delete item.name
            // delete item.weekName
            // delete item.checked
          })
          console.log("固定班制表数据验证通过",params);
          this.$emit('getParams', params);

        } else {
          console.log('固定班制表验证未通过');
          this.$emit('getParams', false);
          return false;
        }
      });
    },
    workingscheduleGetlist(){
      workingscheduleGetlist({
        pageNumber:1,
        pageSize:999,
        name:null
      }).then(res=>{
        if (res.code == 200) {

          this.classesList=[
            {
              label: '快捷选项',
              options:[
                {
                  name:"休息",
                  id:-100,
                }
              ]
            },
            {
              label: '班次列表',
              options:res.data.values
            }
          ]

          // this.classesList=res.data.values
          // this.classesList.push({
          //   name:"休息",
          //   id:-100,
          // })
        }
      }).catch().finally(()=>{

      })
    },
    handleChildEvent(value) {
      console.log('修改的数据ID',this.editId);
      console.log('父组件收到的班次ID',value);
      // 父组件中的方法，用于处理从子组件传递过来的值
      // this.receivedValue = value;
    },
    weekChange(row){
      console.log(row);
      if (row.checked){
        this.handleChange(row)
      }
    },
    // 删除时的回调
    // handleDel(row){
    handleDelOld(row){
      this.W.$myConfirm('warning', this.i18n.t('Are you sure you want to delete it'))
          .then(async () => {

            specialdaysDelete(row.id).then(res => {
              if (res.code == 200) {
                this.getList()
                // 删除成功
                this.W.$tips("success", this.i18n.t('Successfully deleted'));
              }
            })
          })
          .catch(() => {
          });
      // console.log(row);
      // this.tableRow=row
      // this.$refs.deleteRef.open()
    },
    handleDel(row){
    // handleNewDel(row){
      console.log(100, this.specialDatesTableData);
      this.W.$myConfirm('warning', this.i18n.t('Are you sure you want to delete it'))
          .then(async () => {
            console.log(101, this.allSpecialDays);
            console.log(102, row.id);

            this.allSpecialDays.values = this.allSpecialDays.values.filter(item => item.id !== row.id);
            console.log(103, this.allSpecialDays);
            this.getList();
          })
          .catch((err) => {
            console.log(105, err);
          });
      // console.log(row);
      // this.tableRow=row
      // this.$refs.deleteRef.open()
    },
    // 页码变化时
    handleRightCurrentChange(val) {
      this.form.pageNumber = val;
      this.getList()
    },
    // 每页显示的数量变化时
    handleSizeChange(val){
      this.form.pageSize = val
      this.getList()
    },
    // getList(){
    getListOld(){
      var params={
        pageNumber:this.form.pageNumber,
        pageSize:this.form.pageSize,
        attendanceGroupId:this.attendanceGroupId
      }
      this.specialdaysGetlist(params)
    },
    // getNewList(){
      async   getList(){
      console.log(111);
      if(!this.isload) {
        console.log(222);
          var params={
            pageNumber:1,
            pageSize:999999999,
            attendanceGroupId:this.attendanceGroupId
          }

          var res = await specialdaysGetlist(params)
          if (res.code == 200) {
              console.log(382, res);

              this.allSpecialDays=res.data;
              this.isload=true

            }
        }
        console.log("spvalues",this.allSpecialDays.values)
        this.specialDatesTableData.values = this.paginateAndSortStudents(this.allSpecialDays.values, this.form.pageNumber, this.form.pageSize)
        console.log("specialDatesTableData.values",this.specialDatesTableData.values)
        this.specialDatesTableData.totalCount = this.allSpecialDays.values.length
        this.$forceUpdate()
        
    },
    paginateAndSortStudents(students, page, pageSize) {
        
        students.sort(function(a, b) {
          return new Date(a.date) - new Date(b.date);
        });
        console.log("std",students);
        // 计算分页起始索引和结束索引
        const startIndex = (page - 1) * pageSize;
        const endIndex = startIndex + pageSize;

        // return students.filter((student, index) => index >=startIndex && index < endIndex)
        // 返回分页后的学生数据
        return students.slice(startIndex, endIndex);
    },
    // specialdaysGetlist(params){
    // specialdaysOldGetlist(params){
    //   console.log('查询参数',params);
    //   specialdaysGetlist(params).then(res=>{
    //     if (res.code == 200) {

    //       this.specialDatesTableData=res.data

    //     }
    //   }).catch().finally(()=>{
    //     // this.saveLoading=false
    //   })
    // },
    // specialdaysNewGetlist(params){
    specialdaysGetlist(params){
      console.log('查询参数',params);
      specialdaysGetlist(params).then(res=>{
        if (res.code == 200) {
          console.log(447, res);

          this.allSpecialDays=res.data;

        }
      }).catch().finally(()=>{
        // this.saveLoading=false
      })
    },
    handleAdd(type){
      this.handleType="add"
      this.formType=type
      this.dialogVisible=true
      this.rowData=this.allSpecialDays
    },
    handleChangeSpecialOldDates(row){
    // handleChangeSpecialDates(row){
      this.rowData=row
      this.handleType="specialDatesEdit"
      this.formType='2'
      this.dialogVisible=true
    },
    handleChangeSpecialDates(row){
      this.rowData=this.allSpecialDays.values.find(x=>x.id==row.id)
      console.log("修改项",this.rowData, this.allSpecialDays);
      this.handleType="specialDatesEdit"
      this.formType='2'
      this.dialogVisible=true
    },
    handleChange(row){
      this.editId=row.id
      this.handleType="selectShift"
      this.formType='1'
      this.dialogVisible=true
    },
    // 清除临时数据 每次点击新增时候都要调用
    specialdaysRemoveteampdata(){
      specialdaysRemoveteampdata().then(res=>{

      })
    },
  },
  mounted(){
    console.log('detailRow',this.detailRow, this.handleTypeSub);

    if (this.handleTypeSub=="add"){
      // 每次添加时，都删除接口的缓存数据
      this.specialdaysRemoveteampdata()
    }else{
      if (this.handleTypeSub=="edit"){
        var params=JSON.parse(JSON.stringify(this.detailRow))
        this.holidaysIsValid=params.holidaysIsValid

        this.formData.fixedTableData.map((item,index)=>{
          var weekId="g_Week"+(index+1)+"WoringScheduleId"
          console.log('weekId',weekId);
          if (!params[weekId]){
            item.weekId=-100
          }else{
            item.weekId=params["g_Week"+(index+1)+"WoringScheduleId"]
          }
        })
      }
      console.log('this.attendanceGroupId',this.attendanceGroupId);
    }

    // 获取班次列表
    this.workingscheduleGetlist()
    this.getList()
  }
}
</script>
<style scoped lang="scss">
@import '../index.scss';
header{
  margin-left: 20px;
}
.group-type{
  padding: 20px 0px;
}
</style>
<style lang="scss">
.regular{
    .container-search{
     padding: 20px 0px 10px 0px !important;
    }
    }
.switchStyle .el-switch__label {
  position: absolute;
  display: none;
  color: #fff;
}
.el-switch__core{
  background-color: rgba(166, 166, 166, 1) ;
}
.switchStyle .el-switch__label--left {
  z-index: 9;
  left: 30px;
}
.switchStyle .el-switch__label--right {
  z-index: 9;
  left: 4px;
}
.switchStyle .el-switch__label.is-active {
  display: block;
}
.switchStyle.el-switch .el-switch__core,
.el-switch .el-switch__label {
  width: 60px !important;
}
::v-deep .iconfont-KUI {
    margin-right: 5px;
}
</style>
